package com.javacoo.swing.jxbrowser.content;

import java.awt.BorderLayout;
import java.io.DataInputStream;
import java.io.InputStream;
import java.net.URL;

import javax.swing.JFrame;
import javax.swing.WindowConstants;

import com.javacoo.swing.jxbrowser.BaseBrowser;
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserContext;
import com.teamdev.jxbrowser.chromium.ProtocolHandler;
import com.teamdev.jxbrowser.chromium.ProtocolService;
import com.teamdev.jxbrowser.chromium.URLRequest;
import com.teamdev.jxbrowser.chromium.URLResponse;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

/**
 * 从JAR加载HTML
 * <li></li>
 * JxBrowser允许通过URL，本地HTML文件和String加载HTML。通常，诸如HTML文件之类的Java应用程序资源位于包含在应用程序类路径中的JAR存档中。为了能够加载位于JAR存档内的资源，您必须使用以下实现注册自定义ProtocolHandler
 * BrowserContext browserContext = browser.getContext();
 * ProtocolService protocolService = browserContext.getProtocolService();
 * protocolService.setProtocolHandler("jar", new ProtocolHandler() {
 *     @Override
 *     public URLResponse onRequest(URLRequest request) {
 *         try {
 *             URLResponse response = new URLResponse();
 *             URL path = new URL(request.getURL());
 *             InputStream inputStream = path.openStream();
 *             DataInputStream stream = new DataInputStream(inputStream);
 *             byte[] data = new byte[stream.available()];
 *             stream.readFully(data);
 *             response.setData(data);
 *             String mimeType = getMimeType(path.toString());
 *             response.getHeaders().setHeader("Content-Type", mimeType);
 *             return response;
 *         } catch (Exception ignored) {}
 *         return null;
 *     }
 * });
 *
 * 所述getMimeType（）方法返回给定的资源扩展适当mime类型：
 *
 * private static String getMimeType(String path) {
 *     if (path.endsWith(".html")) {
 *         return "text/html";
 *     }
 *     if (path.endsWith(".css")) {
 *         return "text/css";
 *     }
 *     if (path.endsWith(".js")) {
 *         return "text/javascript";
 *     }
 *     return "text/html";
 * }
 *
 * 您可以使用其他扩展和mime类型扩展此方法。
 * 注册ProtocolHandler并定义支持的mime类型后，可以使用标准Java和JxBrowser API从JAR存档加载资源。例如：
 *
 * browser.loadURL(getClass().getResource("index.html").toString());
 * @author: duanyong@jccfc.com
 * @since: 2020/9/25 9:23
 */
public class LoadingHtmlFromJar extends BaseBrowser {
    public static void main(String[] args) {
        final Browser browser = new Browser();
        BrowserView view = new BrowserView(browser);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(view, BorderLayout.CENTER);
        frame.setSize(700, 500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        BrowserContext browserContext = browser.getContext();
        ProtocolService protocolService = browserContext.getProtocolService();
        protocolService.setProtocolHandler("jar", new ProtocolHandler() {
            @Override
            public URLResponse onRequest(URLRequest request) {
                try {
                    URLResponse response = new URLResponse();
                    URL path = new URL(request.getURL());
                    InputStream inputStream = path.openStream();
                    DataInputStream stream = new DataInputStream(inputStream);
                    byte[] data = new byte[stream.available()];
                    stream.readFully(data);
                    response.setData(data);
                    String mimeType = getMimeType(path.toString());
                    response.getHeaders().setHeader("Content-Type", mimeType);
                    return response;
                } catch (Exception ignored) {}
                return null;
            }
        });

        // Assume that we need to load a resource related to this class in the JAR file
        browser.loadURL(LoadingHtmlFromJar.class.getResource("index.html").toString());
    }

    private static String getMimeType(String path) {
        if (path.endsWith(".html")) {
            return "text/html";
        }
        if (path.endsWith(".css")) {
            return "text/css";
        }
        if (path.endsWith(".js")) {
            return "text/javascript";
        }
        return "text/html";
    }
}
